package it.univpm.diiga.memorysim.views;



import it.univpm.diiga.memorysim.data.DataPlugin;
import it.univpm.diiga.memorysim.frames.disk.FileSequence;
import it.univpm.diiga.memorysim.kernel.shared.tree.File;
import it.univpm.diiga.memorysim.kernel.shared.tree.MovingBox;
import it.univpm.diiga.memorysim.kernel.shared.tree.MovingBoxContentProvider;
import it.univpm.diiga.memorysim.kernel.shared.tree.MovingBoxLabelProvider;



import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.part.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.window.Window;

import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.*;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;


public class MemorySecondaryInitialSituation extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "it.univpm.diiga.memorysim.views.MemorySecondaryInitialSituation";

	private TreeViewer viewer;
	private DrillDownAdapter drillDownAdapter;
	private Action action1;
	private Action action2;
	private Action action3;
	private Action doubleClickAction;
	//private MovingBox root;

	protected InputDialog dlg;

	protected InputDialog dlg1;
	
	public MemorySecondaryInitialSituation() {
	}

	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);
		viewer.setContentProvider(new MovingBoxContentProvider());
		viewer.setLabelProvider(new MovingBoxLabelProvider());
		viewer.setInput(getInitial()); 
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "it.univpm.diiga.memorysim.views");
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private Object getInitial() {
		if (DataPlugin.root==null){
		DataPlugin.root = new MovingBox();
		MovingBox queue = new MovingBox("Disco");
		DataPlugin.root.addBox(queue);
		//root.add(queue);
		}
		return DataPlugin.root;
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				MemorySecondaryInitialSituation.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action3);
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
		manager.add(new Separator());
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(action3);
		manager.add(action1);
		manager.add(action2);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action3);
		manager.add(action1);
		manager.add(action2);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				String str="";
				int dim=0;
				dlg = new InputDialog(Display.getCurrent().getActiveShell(),
	    	            "Nome file", "Inserire il nome del file", null, new InputValidator());
				if (dlg.open() == Window.OK) {
					str=dlg.getValue();
					dlg1 = new InputDialog(Display.getCurrent().getActiveShell(),
		    	            "Dimensione file", "Dimensione del file: [Kb]", null, new ValidatorInteger());
					if (dlg1.open() == Window.OK) {
						dim=Integer.parseInt(dlg1.getValue());
						DataPlugin.hddused+=dim;
					}
				}
				
				
				DataPlugin.addFileRequest(str, dim, "", "Creazione file");
				
				/*
				String str="";
				int dim=0;
				while(str.length()<=0) str = JOptionPane.showInputDialog(null, "Nome del file: ",  "Nuovo File", 1);
				while(dim<=0){
					String str1 = JOptionPane.showInputDialog(null, "Dimensione del file: [Kb]",  "Nuovo File", 1);
					try{
					dim=Integer.parseInt(str1);
					}catch(NumberFormatException e){dim=0;}
				}
				File file =  new File(str);
				if(dim>0) file.dimensione=dim;
				if (obj instanceof File) obj.getParent().add(file);
				else  obj.add(file);
				viewer.refresh();
				*/
				ISelection selection = viewer.getSelection();
				MovingBox obj = (MovingBox) ((IStructuredSelection)selection).getFirstElement();
				if (str=="" || dim==0) {}
				else {
					File file =  new File(str);
					if(dim>0) file.dimensione=dim;
					if (obj instanceof File) obj.getParent().add(file);
					else  obj.add(file);
					viewer.refresh();
				}
				
			}
		};
		action1.setText("Aggiungi File");
		action1.setToolTipText("Aggiungi File nella cartella selezionata");
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor(ISharedImages.IMG_OBJ_ADD));
		
		action2 = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				MovingBox obj = (MovingBox) ((IStructuredSelection)selection).getFirstElement();
				boolean risp = MessageDialog.openConfirm(null, "Warning(Cancellazione)", "Sei sicuro di voler cancellare "+obj.getName()+"?");
				if(risp){
					if(!obj.getName().equals("Disco")){
						obj.getParent().remove(obj);
						viewer.refresh();
					}else{ showMessage(obj.getName()+" non puo' essere cancellato");}
				}
			}
		};
		action2.setText("Cancella");
		action2.setToolTipText("Cancella l'elemento selezionato");
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
		action3 = new Action() {
			public void run() {
				String str="";
				dlg = new InputDialog(Display.getCurrent().getActiveShell(),
	    	            "Nome cartella", "Inserire il della cartella", null, new InputValidator());
				if (dlg.open() == Window.OK) {
					str=dlg.getValue();
				}
				/*
				while(str.length()<=0) str = JOptionPane.showInputDialog(null, "Nome della Cartella: ",  "Nuovo Cartella", 1);
				ISelection selection = viewer.getSelection();
				MovingBox obj = (MovingBox) ((IStructuredSelection)selection).getFirstElement();
				if (obj instanceof File) obj.getParent().add(new MovingBox(str));
				else  obj.add(new MovingBox(str));
				viewer.refresh();
				*/
				if (str=="") {}
				else {
					ISelection selection = viewer.getSelection();
					MovingBox obj = (MovingBox) ((IStructuredSelection)selection).getFirstElement();
					if (obj instanceof File) obj.getParent().add(new MovingBox(str));
					else  obj.add(new MovingBox(str));
					viewer.refresh();
				}
				
			}
		};
		action3.setText("Crea Cartella");
		action3.setToolTipText("Crea una sotto-directory");
		action3.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER));
		doubleClickAction = new Action() {
			public void run() {
				new FileSequence(viewer).run();
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Condizione Iniziale Memoria Secondaria",
			message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}	
}

class ValidatorInteger implements IInputValidator {
	public String isValid(String newInt) {
		try{
			int len = Integer.parseInt(newInt);
			if (len>0){
				return null;
			}else return "Inserire un numero valido";
	    }catch(Exception e1){
	    	return "Inserire un numero valido";
	    	}
	    }
}

class InputValidator implements IInputValidator {
	public String isValid(String newInt) {
		if(newInt=="") return "Nome file non valido";
		else return null;
	}
}	